use chrono::Local;
use sea_orm::{ActiveModelTrait, EntityTrait, NotSet, PaginatorTrait};
use sea_orm::ActiveValue::Set;

use common::ctx::get_db_by_key;
use common::error::MyError;
use common::page::{BasePage, PageResult};
use entity::letter;
use entity::prelude::Letter;
use model::game_email::LetterPage;

pub struct LetterManager {}

impl LetterManager {

    pub async fn create_letter(charac_no:i32) ->Result<letter::Model,MyError>{
        let model = letter::ActiveModel {
            letter_id: NotSet,
            charac_no: Set(charac_no),
            send_charac_no: Set(1),
            send_charac_name: Set("dnf-admin-rs".to_string()),
            letter_text: Set("dnf-admin-rs".to_string()),
            reg_date: Set(Local::now().naive_local()),
            stat: Set(0),
        }.insert(&*get_db_by_key("taiwan_cain_2nd")?)
            .await?;
        Ok(model)
    }

    pub async fn page(page:LetterPage) ->Result<PageResult<letter::Model>,MyError>{
        let find = Letter::find();
        //校验并获取分页数据
        let page_data = page.check_page_data();
        //每页大小
        let db_conn = &*get_db_by_key("taiwan_cain_2nd")?;
        let paginator = find.paginate(db_conn, page_data.page_size);

        //执行分页查询
        let record = paginator.fetch_page(page_data.page - 1).await?;
        //总条数
        let total = paginator.num_items().await?;
        //返回分页结果
        Ok(PageResult {
            page: page_data.page,
            page_size: page_data.page_size,
            total,
            record,
        })
    }
    pub async fn remove_letter(id:i32) ->Result<bool,MyError>{
        let res = Letter::delete_by_id(id).exec(&*get_db_by_key("taiwan_cain_2nd")?).await?;
        Ok(res.rows_affected == 1)
    }

}

